package com.xq.jltx.frescosimple.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;



import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;


/**
 * SD卡操作类
 * 
 * @author Administrator
 * 
 */
public class FileUtils {
	private static String SDPath;

	public FileUtils() {
		super();
	}

	/**
	 * 获取文件路径<br />
	 * eg. /data/data/com.example/files/
	 * 
	 * @param mContext
	 * @return
	 */
	public static String getFileDir(Context mContext) {
		return mContext.getFilesDir().getPath() + File.separator;
	}
	
	/**
	 * 获取缓存路径<br />
	 * eg. <li>/data/data/com.example/cache</li> <li>
	 * /sdcard/Android/data/com.example/cache</li>
	 * 
	 * @param mContext
	 *            上下文对象
	 * @return 缓存文件路径
	 */
	public static String getCacheDir(Context mContext) {
		String cachePath = null;
		if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
			// 挂载了外部存储器
			cachePath = mContext.getExternalCacheDir() + File.separator;
		} else {
			cachePath = mContext.getCacheDir() + File.separator;
		}
		return cachePath;
	}
	
	/**
	 * 获取文件的类型
	 * 
	 * @param file
	 *            文件路径
	 * @return
	 */
	public static String getFileType(String file) {
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (inputStream == null) {
			return null;
		}
		byte[] buffer = new byte[2];
		// 文件类型代码
		String filecode = "";
		// 文件类型
		String fileType = "";
		// 通过读取出来的前两个字节来判断文件类型
		try {
			if (inputStream.read(buffer) != -1) {
				for (int i = 0; i < buffer.length; i++) {
					// 获取每个字节与0xFF进行与运算来获取高位，这个读取出来的数据不是出现负数
					// 并转换成字符串
					filecode += Integer.toString((buffer[i] & 0xFF));
				}
				// 把字符串再转换成Integer进行类型判断
				switch (Integer.parseInt(filecode)) {
				case 7790:
					fileType = "exe";
					break;
				case 7784:
					fileType = "midi";
					break;
				case 8297:
					fileType = "rar";
					break;
				case 8075:
					fileType = "zip";
					break;
				case 255216:
					fileType = "jpg";
					break;
				case 7173:
					fileType = "gif";
					break;
				case 6677:
					fileType = "bmp";
					break;
				case 13780:
					fileType = "png";
					break;
				default:
					fileType = "unknown type: " + filecode;
				}
			}
		} catch (Exception e) {
			return fileType;
		}
		return fileType;
	}

	/**
	 * 通过使用自带的文件管理器选中文件，解析它的路径
	 * 
	 * @param mContext
	 * @param uri
	 * @return
	 * @throws URISyntaxException
	 */
	public static String getPath(Context mContext, Uri uri)
			throws URISyntaxException {
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = mContext.getContentResolver().query(uri, projection,
						null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}
		return null;
	}
	
	/**
	 * 根据文件判断该文件是否存在
	 * 
	 * @param context
	 * @param file
	 * @return
	 */
	public static boolean exists(Context context, String file) {
		return new File(file).exists();
	}
	
	/**
	 * 检查文件是否过期 <br />
	 * 若文件不存在，则直接返回true <br />
	 * time指定过期的秒数
	 * 
	 * @param context
	 * @param file
	 * @param time
	 *            单位：秒
	 * @return
	 */
	public static boolean expire(Context context, String file, int time) {
		if (!exists(context, file)) {
			return true;
		}
		File f = new File(file);
		if (Calendar.getInstance().getTimeInMillis() - f.lastModified() > time * 1000) {
			Log.d("file", "file expired");
			return true;
		}
		return false;
	}
	
	/**
	 * 保存文件到包目录的files目录
	 * 
	 * @param context
	 * @param file
	 * @param content
	 * @throws IOException
	 */
	public static void save(Context mContext, String file, String content)
			throws IOException {
		FileOutputStream outputStream = mContext.openFileOutput(file,
				Context.MODE_PRIVATE);
		outputStream.write(content.getBytes());
		outputStream.close();
	}
	
	
	public static String[] findAllFileList(Context context){
		String[] files = null;
		if(context != null){
			files = context.fileList();
		}
		return files;
	}
	
    /**
     * 关闭流
     * 
     * @param closeables
     */
    public static void closeIO(Closeable... closeables) {
        if (null == closeables || closeables.length <= 0) {
            return;
        }
        for (Closeable cb : closeables) {
            try {
                if (null == cb) {
                    continue;
                }
                cb.close();
            } catch (IOException e) {
                throw new RuntimeException(
                        FileUtils.class.getClass().getName(), e);
            }
        }
    }

	/**   
     * 递归查找文件   
     * @param baseDirName  查找的文件夹路径   
     * @param targetFileName  需要查找的文件名   
     * @param fileList  查找到的文件集合   
     */    
    public static void findFiles(String baseDirName, String targetFileName, List<File> fileList) {     
        File baseDir = new File(baseDirName);       // 创建一个File对象   
        if (!baseDir.exists() || !baseDir.isDirectory()) {  // 判断目录是否存在   
            System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");  
        }  
        String tempName = null;     
        //判断目录是否存在      
        File tempFile;  
        File[] files = baseDir.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            tempFile = files[i];  
            if(tempFile.isDirectory()){  
                findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);  
            }else if(tempFile.isFile()){  
                tempName = tempFile.getName();  
                if(targetFileName.equals(tempName)){  
                    // 匹配成功，将文件名添加到结果集   
                    fileList.add(tempFile.getAbsoluteFile());  
                }  
            }  
        }
    }

	public static void findFiles(String baseDirName, List<File> fileList,String[] sufftx) {
		File baseDir = new File(baseDirName);       // 创建一个File对象
		if (!baseDir.exists() || !baseDir.isDirectory()) {  // 判断目录是否存在
			System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");
		}
		String tempName = null;
		//判断目录是否存在
		File tempFile;
		File[] files = baseDir.listFiles();
		for (int i = 0; i < files.length; i++) {
			tempFile = files[i];
			if(tempFile.isDirectory()){
				findFiles(tempFile.getAbsolutePath(), fileList, sufftx);
			}else if(tempFile.isFile()){
				tempName = tempFile.getName();
				for (int j=0; j < sufftx.length; j++){
					if(tempName.endsWith(sufftx[j])){
						// 匹配成功，将文件名添加到结果集
						fileList.add(tempFile.getAbsoluteFile());
					}
				}
			}
		}
	}

	public static String findFile4Asset(Context context,String assetBaseDirName,String[] sufftx){
		AssetManager assetManager = context.getAssets();
		String[] files;
		try {
			files = assetManager.list(assetBaseDirName);
			if(files != null){
				for (String file : files) {
					if(sufftx != null){
						for (int i= 0; i < sufftx.length; i++){
							if(file.contains(sufftx[i])){
								return file;
							}
						}
					}
				}
			}
		} catch (IOException e) {
		}

		return null;
	}

	public static void listAllFiles(String baseDirPath,String baseDirName, List<String> fileList){
		File baseDir = new File(baseDirName);       // 创建一个File对象
		if (!baseDir.exists() || !baseDir.isDirectory()) {  // 判断目录是否存在
			System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");
		}
		String tempName = null;
		//判断目录是否存在
		File tempFile;
		String tempfilePath;
		File[] files = baseDir.listFiles();
		if(files != null){
			for (int i = 0; i < files.length; i++) {
				tempFile = files[i];
				if(tempFile.isDirectory()){
					listAllFiles(baseDirPath,tempFile.getAbsolutePath(), fileList);
				}else if(tempFile.isFile()){
					tempfilePath =  tempFile.getAbsolutePath();
					fileList.add(tempfilePath);
				}
			}
		}

	}
    public static void findAllFiles(String baseDirName, String targetFileName, List<File> fileList) {     
    	File baseDir = new File(baseDirName);       // 创建一个File对象   
    	if (!baseDir.exists() || !baseDir.isDirectory()) {  // 判断目录是否存在   
    		System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");  
    	}  
    	String tempName = null;     
    	//判断目录是否存在      
    	File tempFile;  
    	File[] files = baseDir.listFiles();  
    	for (int i = 0; i < files.length; i++) {  
    		tempFile = files[i];  
    		if(tempFile.isDirectory()){  
    			findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);  
    		}else if(tempFile.isFile()){  
    			tempName = tempFile.getName();
    			if(targetFileName.contains("*")){
    				String[] strs = targetFileName.split("*");
    				List<Boolean> flags = new ArrayList<Boolean>();
    				for(int j=0; i < strs.length; i++){
    					String str = strs[j];
    					if(targetFileName.contains(str)){
    						flags.add(true);
    					}else{
    						flags.add(false);
    					}
    				}
    				boolean flag = true;
    				for(int k =0; k < flags.size(); k++){
    					flag = flag && flags.get(k);
    				}
    			}else{
        			if(targetFileName.equals(tempName)){  
        				// 匹配成功，将文件名添加到结果集   
        				fileList.add(tempFile.getAbsoluteFile());  
        			} 
    			}
 
    		}  
    	}  

    	
    }  
    
    
    public static String getFilePath_Name(String  parentPath, String fileName) {   
    	 List<File> fileList =new ArrayList<File>();
    	findFiles(parentPath,fileName ,fileList);
    	if(fileList!=null && fileList.size() > 0){
    		return fileList.get(0).toString();
    	}
    	return null;
    }
    
	/**
	 * 查找文件的data文件夹里面是否存在文件名为fileName的文件
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static boolean isExitInData(Context context, String fileName){
		String[] files = null;
		if(context != null){
			files = context.fileList();
		}
		if(files != null){
			for(String str : files){
				if(fileName.equals(str)){
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 将data里面的文件名为fileName的文件复制到奥filePath的完整文件路径
	 * @param context
	 * @param fileName
	 * @param filePath
	 * @return
	 */
	public static boolean copyDataFile2SD(Context context,String fileName, String filePath){
		try {
			FileInputStream in = context.openFileInput(fileName);
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream out = new FileOutputStream(filePath);
			int size = in.available();
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && size < FileUtils.getSDAvailableSize()){
				byte[] buf = new byte[1024 * 2];
				int len = 0;
				while((len = in.read(buf)) != -1){
					out.write(buf, 0, len);
				}
				out.flush();
				if(in != null){
					in.close();
					in = null;
				}
				if(out != null){
					out.close();
					out = null;
				}
				return true;
			}else{
				if(in != null){
					in.close();
					in = null;
				}
				if(out != null){
					out.close();
					out = null;
				}
			}
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
		return false;
	}
	/**
	 * 在SD卡根目录上创建文件
	 * 
	 * @param filePath 文件的完整路径
	 * @return
	 */
	public static File createSDFile(String filePath) {
		File file = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			try {
				file.createNewFile();
			} catch (IOException e) {
			}
		}
		return file;
	}

	/**
	 * 创建文件夹
	 * @param filePath
	 * @return
     */
	public static boolean createSDDirectory(String filePath) {
		boolean isSuccess = false;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File file = new File(filePath);
			if (!file.exists()) {
				isSuccess = file.mkdirs();
			}else{
				isSuccess = true;
			}
		}
		return isSuccess;
	}
	/**
	 * 在SD卡的对应目录里面创建创建文件名为fileName的文件
	 * 
	 * @param pathName SD卡目录下的fileName的根目录
	 * @param fileName 要创建的fileName文件名
	 * @return
	 */
	public static File createSDFile(String pathName, String fileName) {
		File file = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			file = new File(Environment.getExternalStorageDirectory()
					.toString()
					+ File.separator
					+ pathName
					+ File.separator
					+ fileName);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
		}
		try {
			file.createNewFile();
		} catch (IOException e) {
		}
		return file;
	}
	
	/**
	 * 判断是否存在文件或者存在的文件夹是否存在
	 * 
	 * @param filePath
	 * @return
	 */
	public static boolean isExistFile(String filePath) {
		File file = null;
		if (filePath != null && Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			file = new File(filePath);
			if (file != null && file.exists()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}

	/**
	 * 判断是否存在文件或者存在的文件夹是否为空
	 * 
	 * @param dirName 完整的文件路径
	 * @return
	 */
	public static boolean isExistFiles(String filePath) {
		File file = null;
		if (filePath != null && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			file = new File(filePath);
			if (file.exists()) {
				if (file.isDirectory()) {
					if (file.list().length != 0) {
						return true;
					} else {
						return false;
					}
				} else {
					return true;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}

	}

	/**
	 * 在SD卡上创建目录
	 * 
	 * @param dirName
	 * @return
	 */
	public static File createSDDir(String dirName) {
		File file = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			file = new File(Environment.getExternalStorageDirectory()
					.toString() + File.separator + dirName);
			if (!file.exists()) {
				file.mkdirs();
			}
		}
		return file;
	}

	/**
	 * 判断SD卡上的文件夹是否存在
	 * 
	 * @param fileName 文件在SD卡上相对的文件路径
	 * @return
	 */
	public static boolean isFileExist(String filePath) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File file = new File(Environment.getExternalStorageDirectory()
					.toString() + File.separator + filePath);
			return file.exists();
		}
		return false;
	}

	/**
	 * 获取当前设备的SD卡根存储目录
	 * 
	 * @return
	 */
	public static String getSDPath() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			SDPath = Environment.getExternalStorageDirectory().toString()
					+ File.separator;
			return SDPath;
		}
		return "";
	}

	/**
	 * 获取文件路径String
	 * 
	 * @param dirName 相对于SD卡的文件根目录
	 * @param fileName 文件名
	 * @return
	 */
	public static String getFilePath2String(String dirName, String fileName) {
		return SDPath + dirName + File.separator + fileName;
	}
	/**
	 * 将完整src的完整文件路径的文件复制到文件夹
	 * @param src 被复制的文件的完整文件路径
	 * @param dir 要复制的目的文件夹的完整文件路径
	 * @return
	 * @throws Exception
	 */
	public static String copyFile(String src, String dir) throws Exception
	{
		if(src == null || dir == null)
			return null;
		File fsrc = new File(src);
		if(fsrc.exists())
		{
			if(dir.lastIndexOf('/') != dir.length()-1)
			{
				dir += "/";
			}
			//返回由此抽象路径名表示的文件或目录的名称。该名称是路径名名称序列中的最后一个名称。如果路径名名称序列为空，则返回空字符串
			String dst = dir+fsrc.getName();
			FileInputStream fis = new FileInputStream(fsrc);
			FileOutputStream fos = new FileOutputStream(dst);
			byte[] buffer = new byte[fis.available()];
			int size = 0;
			while((size = fis.read(buffer, 0, buffer.length)) != -1)
			{
				fos.write(buffer, 0, size);
			}
			fos.close();
			fis.close();
			return dst;
		}
		return null;
	}
	
	public static String copyFileTo(String src, String dst) throws Exception
	{
		if(src == null || dst == null)
			return null;
		File fsrc = new File(src);
		if(fsrc.exists())
		{
			int index = dst.lastIndexOf('/');
			if(index != -1)
			{
				File dir = new File(dst.substring(0, index));
				if(dir.exists() == false)
				{
					if(dir.mkdirs() == false)
						return null;
				}
			}
			FileInputStream fis = new FileInputStream(fsrc);
			FileOutputStream fos = new FileOutputStream(dst);
			byte[] buffer = new byte[10240];
			int size = 0;
			while((size = fis.read(buffer, 0, buffer.length)) != -1)
			{
				fos.write(buffer, 0, size);
			}
			fos.close();
			fis.close();
			return dst;
		}
		return null;
	}
	/**
	 * 获取对应文件目录下的文件的File
	 * 
	 * @param dirName
	 * @param fileName
	 * @return
	 */
	public static File getFilePath(String dirName, String fileName) {
		File file = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String dirPath;
			if (dirName != null) {
				dirPath = Environment.getExternalStorageDirectory().toString()
						+ File.separator + dirName + File.separator;
			} else {
				dirPath = SDPath;
			}
			file = new File(dirPath + fileName);
			if (!file.getParentFile().exists()) {
				if(!file.getParentFile().mkdirs()){
					return null;
				}
			}
		}
		return file;
	}

	/**
	 * 获取SD卡的剩余容量，单位是Byte
	 * 
	 * @return
	 */
	public static long getSDAvailableSize() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File pathFile = Environment.getExternalStorageDirectory();
			// Retrieve overall information about the space on a filesystem.
			// This is a Wrapper for Unix statfs().
			StatFs statfs = new StatFs(pathFile.getPath());
			// 获取SDCard上每一个block的SIZE
			long nBlockSize = statfs.getBlockSize();
			// 获取可供程序使用的Block的数量
			// long nAvailBlock = statfs.getAvailableBlocksLong();
			long nAvailBlock = statfs.getAvailableBlocks();
			// 计算SDCard剩余大小Byte
			long nSDFreeSize = nAvailBlock * nBlockSize;
			return nSDFreeSize;
		}
		return 0;
	}

	/**
	 * 获取SD卡的总容量，单位是Byte
	 * 
	 * @return
	 */
	public static long getSDCountSize() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File pathFile = Environment.getExternalStorageDirectory();
			// Retrieve overall information about the space on a filesystem.
			// This is a Wrapper for Unix statfs().
			StatFs statfs = new StatFs(pathFile.getPath());
			// 获取SDCard上每一个block的SIZE
			long nBlockSize = statfs.getBlockSize();
			// 获取可供程序使用的Block的数量
			// long nCountBlock = statfs.getBlockCountLong();
			long nCountBlock = statfs.getBlockCount();
			// 计算SDCard剩余大小Byte
			long nSDFreeSize = nCountBlock * nBlockSize;
			return nSDFreeSize;
		}
		return 0;
	}

	/**
	 * 将输入流写入到指定目录的SD卡中
	 * 
	 * @param path 要输出文件在SD卡中相对根目录
	 * @param fileName 输出的文件名
	 * @param input 文件的输入流
	 * @return
	 */
	public static boolean write2SDFromInput(String path, String fileName, InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			int size = input.available();
			// 拥有可读可写权限，并且有足够的容量
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)
					&& size < getSDAvailableSize()) {
					String dirPath;
				if (path != null) {
					dirPath = Environment.getExternalStorageDirectory().toString()
							+ File.separator + path + File.separator;
				} else {
					dirPath = SDPath;
				}
				file = new File(dirPath + fileName);
				if (!file.getParentFile().exists()) {
					if(!file.getParentFile().mkdirs())
						return false;
				}
				output = new FileOutputStream(file);
				byte buffer[] = new byte[1024 * 2];
				int len = 0;
				while ((len = input.read(buffer)) != -1) {
					output.write(buffer, 0, len);
				}
				output.flush();
			}
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 将String写入到指定的File路径中
	 * @param filePath
	 * @param srcStr
     * @return
     */
	public static boolean write2SDFromString(String filePath,String srcStr){
		boolean isSuccess = false;
		if(!TextUtils.isEmpty(filePath) && srcStr != null){
			File file = new File(filePath);
			if(!file.getParentFile().exists()){
				File parentFile = file.getParentFile();
				if(!parentFile.mkdirs()){
					isSuccess =  false;
					return isSuccess;
				}
			}

			try {
				byte[] buffer = srcStr.getBytes();
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(buffer);
				fos.flush();
				fos.close();
				isSuccess = true;
			} catch (FileNotFoundException e) {
				isSuccess = false;
			}catch (IOException e){
				isSuccess = false;
			}
		}
		return isSuccess;

	}
	/**
	 * 将输入流写入到指定的File路径中
	 * 
	 * @param filePath 输出到SD卡的完整路径名
	 * @param input 输入流
	 * @return
	 */
	public static boolean write2SDFromInput(String filePath, InputStream input) {
		if(filePath==null || input == null)
			return false;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			int size = input.available();
			// 拥有可读可写权限，并且有足够的容量
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)
					&& size < getSDAvailableSize()) {
				bis = new BufferedInputStream(input);
				File outFile = new File(filePath);
				if (!outFile.getParentFile().exists()) {
					if(!outFile.getParentFile().mkdirs()){
						return false;
					}
				}
				bos = new BufferedOutputStream(new FileOutputStream(outFile));
				byte buffer[] = new byte[1024 * 2];
				int len = 0;
				while ((len = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				bos.flush();
			}
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}

	/**
	 * 将输入流转换成字符串
	 * 
	 * @param input
	 * @return
	 */
	public static String inputStream2String(InputStream input) {
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(input));
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			if (reader != null) {
				reader.close();
			}
		} catch (IOException e) {
		}
		return builder.toString();
	}

	/**
	 *  读取本地文本文件
	 * @param filePath 文件在SD卡的完整路径
	 * @return
	 */
	public static String ReadFile2String(String filePath) {
		File file = null;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = null;
		file = new File(filePath);
		if (file.exists()) {
			try {
				reader = new BufferedReader(new InputStreamReader(
						new FileInputStream(file)));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line).append("\n");
				}
				if (reader != null) {
					reader.close();
				}
			} catch (FileNotFoundException e) {
			} catch (IOException e) {
			}
			return builder.toString();
		} else {
			return null;
		}
	}

	/**
	 * 删除文件包括文件夹
	 * @param filePath 完整文件路径名
	 * @return
	 */
	public static boolean deleteFile(String filePath) {
		if(MyStringUtils.isBlank(filePath)) {
			return true;
		} else {
			File file = new File(filePath);
			if(!file.exists()) {
				return true;
			} else if(file.isFile()) {
				return file.delete();
			} else if(!file.isDirectory()) {
				return false;
			} else {
				File[] arr$ = file.listFiles();
				int len$ = arr$.length;

				for(int i$ = 0; i$ < len$; ++i$) {
					File f = arr$[i$];
					if(f.isFile()) {
						f.delete();
					} else if(f.isDirectory()) {
						deleteFile(f.getAbsolutePath());
					}
				}

				return file.delete();
			}
		}
	}
	private static String TAG = "FileUtils";
	/**
	 * 删除指定路径下的文件，包括文件和文件目录
	 * @param filePath
	 * @return 删除成功返回true,返回失败返回false
	 */
	public static boolean deleteFiles(String filePath){
		return deleteFile(filePath);
//		//定义文件路径
//		if(filePath != null){
//			File file = new File(filePath);
//			if(file != null && file.exists()){
//				PLog.out(TAG,filePath + "存在");
//				if(file.isDirectory()){
//
//					File[] files = file.listFiles();
//					PLog.out(TAG,filePath + "是目录，所有子目录为：" + files.toString());
//					for(File subFile : files){
//						if(subFile.isDirectory()){
//							deleteFiles(subFile.getPath());
//						}else{
//							PLog.out(TAG,"将删除文件" +subFile.getPath());
//							subFile.delete();
//						}
//					}
//				}
//				PLog.out(TAG,"将删除文件" +file.getPath());
//				return file.delete();//删除单个文件
//			}
//		}
//
//		return false;
	}
	
	/**
	 * 更改文件夹名
	 * @param src
	 * @param dest
	 * @return
	 */
	public static boolean renameToNewFile(String src, String dest)  
	{  
	       File srcDir = new File(src);  
	       boolean isOk = srcDir.renameTo(new File(dest));  
	       return isOk;  
	 } 
	
	
	public static String search(String parent, String fileName) {
		File parentFile = new File(parent);
		if(parentFile.isDirectory()){
			File[] list = parentFile.listFiles();
			for (File file : list) {
				if(file.isDirectory()){
					search(file.getPath(), fileName);
				}else{
					if(fileName.equals(file.getName())){
						return file.getAbsolutePath();
					}
				}
			}
		}
		return null;
	}
	
	
	/**
	 * 将输入流写入到指定目录的SD卡中
	 * 
	 * @param path 要输出文件在SD卡中相对根目录
	 * @param fileName 输出的文件名
	 * @param input 文件的输入流
	 * @return
	 */
	public static boolean writeFile2SDFromInput(String fileName,
			InputStream input) {

		if (fileName == null || input == null)
			return false;
		File file = null;
		OutputStream output = null;
		try {
			int size = input.available();
			// 拥有可读可写权限，并且有足够的容量
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)	&& size < getSDAvailableSize()) {
				fileName = Environment.getExternalStorageDirectory().toString()	+ File.separator + fileName;
				file = new File(fileName);
				if (!file.getParentFile().exists()) {
					if (!file.getParentFile().mkdirs())
						return false;
				}
				output = new FileOutputStream(file);
				byte buffer[] = new byte[1024 * 2];
				int len = 0;
				while ((len = input.read(buffer)) != -1) {
					output.write(buffer, 0, len);
				}
				output.flush();
			}
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					return false;
				}
			}
		}
		return true;
	}
	
	/*
	 * 在某文件下找 后缀为suffix的文件，找到立即返回
	 */
	public static String findFile(String path,String suffix){
		if(path!=null && suffix !=null){
			File file = new File(path);
			if(file.exists() && file.isDirectory()){
				String[] files = file.list();
				for(int i = 0; i<files.length ;i++){
					if(files[i].contains(suffix))
						return files[i];
				}
			}
		}
		return null;
	}
	
	/**
	 * 将一个字符串转化为输入流
	 */
	public static InputStream string2Stream(String string) {
		if (string != null && !string.trim().equals("")) {
			try {
				ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(
						string.getBytes());
				return tInputStringStream;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

	public static File getCacheDirectory(Context context) {
		return getCacheDirectory(context, true);
	}

	public static File getCacheDirectory(Context context, boolean preferExternal) {
		File appCacheDir = null;
		if(preferExternal && "mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
			appCacheDir = getExternalCacheDir(context);
		}

		if(appCacheDir == null) {
			appCacheDir = context.getCacheDir();
		}

		if(appCacheDir == null) {
			String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/";
			appCacheDir = new File(cacheDirPath);
		}

		return appCacheDir;
	}

	public static File getAllPathFile(Context context, String sdCacheDir,String dataCachDir){
		File appCacheDir = null;
		if("mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
			String filePath = Environment.getExternalStorageDirectory() .toString() + File.separator + sdCacheDir;
			appCacheDir = new File(filePath);
		}

		if(appCacheDir == null) {
			String[] files = dataCachDir.split("/");
			File fileDir = null;
			for(int i=0; i < files.length; i++){
				String fileName = files[i];
				if(fileName != null && fileName.length() > 0){
					if(fileDir == null){
						fileDir = context.getDir(fileName, Context.MODE_PRIVATE);
					}else{
						fileDir = new File(fileDir,fileName);
					}

				}

			}

			if(fileDir != null){
				appCacheDir = fileDir;
			}else{
				appCacheDir = context.getCacheDir();
			}

		}
		return appCacheDir;
	}


	public static File getOwnCacheDirectory(Context context, String sdCacheDir,String dataCachDir) {
		File appCacheDir = null;
		if("mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
			appCacheDir = new File(Environment.getExternalStorageDirectory(), sdCacheDir);
		}

		if(appCacheDir == null || !appCacheDir.exists() && !appCacheDir.mkdirs()) {
			appCacheDir = context.getCacheDir();
			appCacheDir = new File(appCacheDir,dataCachDir);
		}

		return appCacheDir;
	}


	public static File getExternalCacheDir(Context context) {
		File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
		File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
		if(!appCacheDir.exists()) {
			if(!appCacheDir.mkdirs()) {
				return null;
			}

			try {
				(new File(appCacheDir, ".nomedia")).createNewFile();
			} catch (IOException var4) {
			}
		}

		return appCacheDir;
	}

	private static boolean hasExternalStoragePermission(Context context) {
		int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
		return perm == 0;
	}

	public static String getUrlFileName(String url) {
		if(!MyStringUtils.isEmpty(url)) {
			int index = url.lastIndexOf(63);
			String filename;
			if(index > 1) {
				filename = url.substring(url.lastIndexOf(47) + 1, index);
			} else {
				filename = url.substring(url.lastIndexOf(47) + 1);
			}

			return filename;
		} else {
			return "";
		}
	}

	/**
	 * 获取路径里面的文件名
	 * @param filePath
	 * @return
     */
	public static String getNameFormPath(String filePath){
		if(filePath != null){
			String fileStr = filePath;
			int end = fileStr.lastIndexOf("/");
			if(end != -1){
				fileStr = fileStr.substring(end + 1, fileStr.length());
			}
			return fileStr;
		}else{
			return null;
		}
	}
	/**
	 * 获取下载地址的文件名
	 * @param url
	 * @return
	 */
	public static String getDownNameFormUrl(String url){
		if(url != null){
			String fileStr = url;
			int end = fileStr.lastIndexOf("/");
			if(end != -1){
				fileStr = fileStr.substring(end + 1, fileStr.length());
			}

			if(!fileStr.endsWith(".zip") && !fileStr.endsWith(".json")){
				int pos = fileStr.lastIndexOf(".");
				if(pos != -1){
					fileStr = fileStr.substring(0, pos) + ".img";
				}
			}
			return fileStr;
		}else{
			return null;
		}
	}

	public static String getUrlFileBaseName(String url) {
		if(!MyStringUtils.isEmpty(url)) {
			String filename = getUrlFileName(url);
			int dotIndex = filename.lastIndexOf(46);
			String filenameWithoutExtension;
			if(dotIndex == -1) {
				filenameWithoutExtension = filename.substring(0);
			} else {
				filenameWithoutExtension = filename.substring(0, dotIndex);
			}

			return filenameWithoutExtension;
		} else {
			return "";
		}
	}

	public static String getUrlFileExtension(String url) {
		if(!MyStringUtils.isEmpty(url)) {
			String filename = getUrlFileName(url);
			int i = filename.lastIndexOf(46);
			if(i > 0 && i < filename.length() - 1) {
				return filename.substring(i + 1).toLowerCase();
			}
		}

		return "";
	}

	public static String getFileBaseName(String filename) {
		if(filename != null && filename.length() > 0) {
			int dot = filename.lastIndexOf(46);
			if(dot > -1 && dot < filename.length()) {
				return filename.substring(0, dot);
			}
		}

		return filename;
	}

	/**
	 * 判断文件夹是否存在
	 * @param directoryPath
	 * @return
	 */
	public static boolean isFolderExist(String directoryPath) {
		if(MyStringUtils.isBlank(directoryPath)) {
			return false;
		} else {
			File dire = new File(directoryPath);
			return dire.exists() && dire.isDirectory();
		}
	}

	public static boolean deleteFile(File path) {
		return path == null?false:deleteFile(path.getAbsolutePath());
	}

	public static String showFileSize(long size) {
		String fileSize;
		if((double)size < 1024.0D) {
			fileSize = size + "B";
		} else if((double)size < 1048576.0D) {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1024.0D)}) + "KB";
		} else if((double)size < 1.073741824E9D) {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1048576.0D)}) + "MB";
		} else {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1.073741824E9D)}) + "GB";
		}

		return fileSize;
	}

	public static boolean createIfNoExists(String path) {
		File file = new File(path);
		boolean mk = false;
		if(!file.exists()) {
			mk = file.mkdirs();
		}

		return mk;
	}

	public static long getFileSizes(File f) throws Exception {
		long size = 0L;
		File[] flist = f.listFiles();

		for(int i = 0; i < flist.length; ++i) {
			if(flist[i].isDirectory()) {
				size += getFileSizes(flist[i]);
			} else {
				size += getFileSize(flist[i]);
			}
		}

		return size;
	}

	public static long getFileSize(File file) throws Exception {
		long size = 0L;
		if(file.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			size = (long)fis.available();
		} else {
			file.createNewFile();
		}

		return size;
	}

	public static String generateFileSize(long size) {
		String fileSize;
		if((double)size < 1024.0D) {
			fileSize = size + "B";
		} else if((double)size < 1048576.0D) {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1024.0D)}) + "KB";
		} else if((double)size < 1.073741824E9D) {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1048576.0D)}) + "MB";
		} else {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1.073741824E9D)}) + "GB";
		}

		return fileSize;
	}

	public static String generateNetworkSpeed(long size, long time) {
		String fileSize;
		if((double)size < 1024.0D) {
			fileSize = size + "B";
		} else if((double)size < 1048576.0D) {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1024.0D)}) + "KB";
		} else if((double)size < 1.073741824E9D) {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1048576.0D)}) + "MB";
		} else {
			fileSize = String.format("%.1f", new Object[]{Double.valueOf((double)size / 1.073741824E9D)}) + "GB";
		}

		return fileSize;
	}


	public static boolean moveFile(String sourceFilePath, String destFilePath) {
		if(!TextUtils.isEmpty(sourceFilePath) && !TextUtils.isEmpty(destFilePath)) {
			return moveFile(new File(sourceFilePath), new File(destFilePath));
		} else {
			return false;
		}
	}

	public static boolean moveFile(File srcFile, File destFile) {
		boolean result;
		boolean rename = srcFile.renameTo(destFile);
		if(!rename) {
			result =copyFileV2(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
			deleteFile(srcFile.getAbsolutePath());
		}else{
			result = rename;
		}
		return result;
	}

	public static boolean copyFileV2(String sourceFilePath, String destFilePath) {
		boolean result = false;
		FileInputStream inputStream = null;

		try {
			inputStream = new FileInputStream(sourceFilePath);
			result = writeFile((String)destFilePath, (InputStream)inputStream);
		} catch (FileNotFoundException var4) {
//			throw new RuntimeException("FileNotFoundException occurred. ", var4);
			result = false;
		}

		return result;
	}

	public static boolean writeFile(String filePath, InputStream stream) {
		return writeFile(filePath, stream, false);
	}

	public static boolean writeFile(String filePath, InputStream stream, boolean append) {
		return writeFile(filePath != null?new File(filePath):null, stream, append);
	}

	public static boolean writeFile(File file, InputStream stream) {
		return writeFile(file, stream, false);
	}

	public static boolean writeFile(File file, InputStream stream, boolean append) {
		FileOutputStream o = null;
		boolean result = false;
		try {
			makeDirs(file.getAbsolutePath());
			o = new FileOutputStream(file, append);
			byte[] e = new byte[1024];
			boolean length = true;

			int length1;
			while((length1 = stream.read(e)) != -1) {
				o.write(e, 0, length1);
			}

			o.flush();
			result= true;
		} catch (FileNotFoundException var16) {
//			throw new RuntimeException("FileNotFoundException occurred. ", var16);
			result= false;
		} catch (IOException var17) {
//			throw new RuntimeException("IOException occurred. ", var17);
			result= false;
		} finally {
			if(o != null) {
				try {
					o.close();
					stream.close();
				} catch (IOException var15) {
					result= false;
//					throw new RuntimeException("IOException occurred. ", var15);
				}
			}

		}
		return result;
	}
	public static List<String> readFileToList(String filePath, String charsetName) {
		File file = new File(filePath);
		ArrayList fileContent = new ArrayList();
		if(file != null && file.isFile()) {
			BufferedReader reader = null;

			try {
				InputStreamReader e = new InputStreamReader(new FileInputStream(file), charsetName);
				reader = new BufferedReader(e);
				String line = null;

				while((line = reader.readLine()) != null) {
					fileContent.add(line);
				}

				reader.close();
				ArrayList var7 = fileContent;
				return var7;
			} catch (IOException var16) {
				throw new RuntimeException("IOException occurred. ", var16);
			} finally {
				if(reader != null) {
					try {
						reader.close();
					} catch (IOException var15) {
						throw new RuntimeException("IOException occurred. ", var15);
					}
				}

			}
		} else {
			return null;
		}
	}

	public static String getFileNameWithoutExtension(String filePath) {
		if(MyStringUtils.isEmpty(filePath)) {
			return filePath;
		} else {
			int extenPosi = filePath.lastIndexOf(".");
			int filePosi = filePath.lastIndexOf(File.separator);
			return filePosi == -1?(extenPosi == -1?filePath:filePath.substring(0, extenPosi)):(extenPosi == -1?filePath.substring(filePosi + 1):(filePosi < extenPosi?filePath.substring(filePosi + 1, extenPosi):filePath.substring(filePosi + 1)));
		}
	}

	public static String getFileName(String filePath) {
		if(MyStringUtils.isEmpty(filePath)) {
			return filePath;
		} else {
			int filePosi = filePath.lastIndexOf(File.separator);
			return filePosi == -1?filePath:filePath.substring(filePosi + 1);
		}
	}

	public static String getFolderName(String filePath) {
		if(MyStringUtils.isEmpty(filePath)) {
			return filePath;
		} else {
			int filePosi = filePath.lastIndexOf(File.separator);
			return filePosi == -1?"":filePath.substring(0, filePosi);
		}
	}

	public static String getFileExtension(String filePath) {
		if(MyStringUtils.isBlank(filePath)) {
			return filePath;
		} else {
			int extenPosi = filePath.lastIndexOf(".");
			int filePosi = filePath.lastIndexOf(File.separator);
			return extenPosi == -1?"":(filePosi >= extenPosi?"":filePath.substring(extenPosi + 1));
		}
	}

	public static boolean makeDirs(String filePath) {
		String folderName = getFolderName(filePath);
		if(MyStringUtils.isEmpty(folderName)) {
			return false;
		} else {
			File folder = new File(folderName);
			return folder.exists() && folder.isDirectory()?true:folder.mkdirs();
		}
	}

	public static boolean makeFolders(String filePath) {
		return makeDirs(filePath);
	}

	public static boolean makeFolders(File filePath) {
		return makeDirs(filePath.getAbsolutePath());
	}

	public static boolean isFileExistV2(String filePath) {
		if(MyStringUtils.isBlank(filePath)) {
			return false;
		} else {
			File file = new File(filePath);
			return file.exists() && file.isFile();
		}
	}

}
